//
//  PersonalInfoTableViewController.m
//  CleanerAir_Project
//
//  Created by 付亚杰 on 16/6/23.
//  Copyright © 2016年 Beijing Colin El Internet. All rights reserved.
//

#import "PersonalInfoTableViewController.h"
#import "ChangePersonalInfoViewController.h"
#import "NJImageCropperViewController.h"
#import "MBProgressHUD.h"
#import <MobileCoreServices/MobileCoreServices.h>


#define ORIGINAL_MAX_WIDTH 640.0f

@interface PersonalInfoTableViewController ()<UIImagePickerControllerDelegate ,NJImageCropperDelegate>{
    
        
        MBProgressHUD	*indicator;
    
    PersonalInformationModel *model;
}

@property (weak, nonatomic) IBOutlet UILabel *ids;

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;

@property (weak, nonatomic) IBOutlet UILabel *nickName;

@property (weak, nonatomic) IBOutlet UILabel *sex;

@property (weak, nonatomic) IBOutlet UILabel *brithday;

@property (weak, nonatomic) IBOutlet UILabel *email;

@property (weak, nonatomic) IBOutlet UILabel *address;

@property (weak, nonatomic) IBOutlet UILabel *instructions;
@end

@implementation PersonalInfoTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"个人信息";
    
//     model = [LoginSingleton sharedLoginSingleton].perInfoModel;
    
    
    [self initSubView];
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:(CGRectZero)];
    
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"return"] style:(UIBarButtonItemStylePlain) target:self action:@selector(popViewController)];
    self.navigationItem.leftBarButtonItem = leftBtn;
    
    [self.headImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeHeadImage)]];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    
}

- (void)popViewController{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)initSubView{ 
    
    if (model != nil) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.headImageView sd_setImageWithURL:[NSURL URLWithString:Get_HeadImage_UrlString(model.avatar)] placeholderImage:[UIImage imageNamed:@"个人注册.png"]];
            
            self.nickName.text = model.nickname;
            self.instructions.text = model.mood;
            self.brithday.text = model.birthday;
            self.email.text = model.email;
            self.ids.text = model.ids;
            self.sex.text = model.sex;
            self.address.text = model.address;
            self.instructions.text = model.mood;
            
        });
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -- 选择头像
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.row == 0) {
//        [self changeHeadImage];
//    }
}

#pragma mark -- 改变头像
- (void)changeHeadImage{
    
    __weak __typeof(self) weakSelf = self;
    UIAlertController *alterController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择图片来源" preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    UIAlertAction *cameralAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        if ([weakSelf isCameraAvailable] && [weakSelf doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([weakSelf isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [weakSelf presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                     //                                 NSLog(@"Picker View Controller is presented");
                                 }];
        }
        
    }];
    
    UIAlertAction *photoAction =[UIAlertAction actionWithTitle:@"从相册中选取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        // 从相册中选取
        if ([weakSelf isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [weakSelf presentViewController:controller
                                   animated:YES
                                 completion:^(void){
                                     //                                 NSLog(@"Picker View Controller is presented");
                                 }];
        }
        
    }];
    
    [alterController addAction:cameralAction];
    [alterController addAction:photoAction];
    [alterController addAction:cancelAction];
    
    
    [self presentViewController:alterController animated:YES completion:nil];
    
}


#pragma mark VPImageCropperDelegate
- (void)imageCropper:(NJImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        self.headImageView.image = editedImage;
    });
    
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
#pragma mark - 上传头像
        
        [self uploadImage:editedImage];
    }];
}

- (void)imageCropperDidCancel:(NJImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark - 上传头像
- (void)uploadImage:(UIImage *)image{
    
//    [self showIndicator:@"正在上传头像，请稍候..."];
    
    NSData *data = UIImageJPEGRepresentation(image,0.75);
    
}




#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        NJImageCropperViewController *imgEditorVC = [[NJImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}



#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//
//    return 0;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//
//    return 0;
//}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//     Get the new view controller using [segue destinationViewController].
//     Pass the selected object to the new view controller.
    
    
    __weak __typeof(self) weakSelf = self;
    
    if ([segue.identifier isEqualToString:@"NICK_NAME"]) {
        
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changeType = NICK_NAME;
        ((ChangePersonalInfoViewController *)segue.destinationViewController).info = self.nickName.text;
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changePerInfoBlock = ^(NSString *info){
            
            if (![info isEqualToString:@""]) {
                
                model.nickname = info;
            }
            
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [weakSelf changePerInfo];
            
        };
        
    }else if([segue.identifier isEqualToString:@"SEX"]){
        
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changeType = SEX;
                ((ChangePersonalInfoViewController *)segue.destinationViewController).info = self.sex.text;
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changePerInfoBlock = ^(NSString *info){
            
            if (![info isEqualToString:@""]) {
                
                model.sex = info;
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [weakSelf changePerInfo];
        };
        
    }else if([segue.identifier isEqualToString:@"BRITHDAY"]){
        
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changeType = BRITHDAY;
                ((ChangePersonalInfoViewController *)segue.destinationViewController).info = self.brithday.text;
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changePerInfoBlock = ^(NSString *info){
            
            if (![info isEqualToString:@""]) {
                
                model.birthday = info;
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [weakSelf changePerInfo];
        };
        
    }else if([segue.identifier isEqualToString:@"EMAIL"]){
        
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changeType = EMAIL;
                ((ChangePersonalInfoViewController *)segue.destinationViewController).info = self.email.text;
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changePerInfoBlock = ^(NSString *info){
            
            if (![info isEqualToString:@""]) {
                
                model.email = info;
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [weakSelf changePerInfo];
        };
        
    }else if([segue.identifier isEqualToString:@"ADDRESS"]){
        
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changeType = ADDRESS;
                ((ChangePersonalInfoViewController *)segue.destinationViewController).info = self.address.text;
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changePerInfoBlock = ^(NSString *info){
            
            if (![info isEqualToString:@""]) {
                
                model.address = info;
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [weakSelf changePerInfo];
        };
        
    }else if([segue.identifier isEqualToString:@"INTRODUCTION"]){
        
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changeType = INTRODUCTION;
                ((ChangePersonalInfoViewController *)segue.destinationViewController).info = self.instructions.text;
        ((ChangePersonalInfoViewController *)segue.destinationViewController).changePerInfoBlock = ^(NSString *info){
            
            if (![info isEqualToString:@""]) {
                
                model.mood = info;
            }
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [weakSelf changePerInfo];
        };
        
    }
    

    
    self.hidesBottomBarWhenPushed = YES;
    
}


- (void)createIndicator
{
    if(indicator != nil)
        return;
    
    indicator = [[MBProgressHUD alloc] initWithView:self.view];
    indicator.color = rgb(104, 104, 104);
    indicator.labelFont = [UIFont systemFontOfSize:13];
    indicator.userInteractionEnabled = YES;
    
    [self.view addSubview:indicator];
}

- (void)showIndicator:(NSString*)_labelText
{
    [self createIndicator];
    
    [self.view bringSubviewToFront:indicator];
    indicator.labelText = [NSString stringWithString:_labelText];
    [indicator show:YES];
}

- (void)hideIndicator
{
    [indicator hide:YES];
}


#pragma mark -- 修改个人信息
- (void)changePerInfo{
    
   
    
//    [HTTPManager post:GET_URLString(@"Api/Member/infoSub") parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        NSLog(@"%@",responseObject[@"msg"]);
//        
//        [self hideIndicator];
//        if ([responseObject[@"msg"] isEqualToString:@"成功"]) {
//            
//            [ShowMessage showCenterViewMessage:@"修改成功"];
//            [weakSelf initSubView];
////            [weakSelf.navigationController popViewControllerAnimated:YES];
//        }else{
//            [ShowMessage showCenterViewMessage:responseObject[@"msg"]];
//        }
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@",operation.responseObject);
//        [self hideIndicator];
//    }];
    
}

@end
